package com.ruoyi.web.utils;

import com.ruoyi.common.core.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取usreId的工具类
 */
public class UserMsgUtil {

    /**
     * 获取当前登录用户的userId
     */
    public static Long getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                LoginUser loginUser = (LoginUser) principal;
                // 获取userId
                Long userId = loginUser.getUserId();
                return userId;
            }
        }
        return null;
    }

    /**
     * 获取当前登录用户的userName
     */
    public static String getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                LoginUser loginUser = (LoginUser) principal;
                // 获取userId
                String username = loginUser.getUsername();
                return username;
            }
        }
        return null;
    }

    /**
     * 拼接前缀
     */
    public static String subAvatar(String avatar) {
        // 获取本机ip
        try {
            return "http://" + InetAddress.getLocalHost().getHostAddress() + ":8080" + avatar;
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }
}
